package com.google.code.jcooky.chat.client.daemon;

import java.util.List;
import java.util.Vector;

import com.google.code.jcooky.chat.client.service.ChatService;
import com.google.code.jcooky.chat.commons.jrc.Message;
import com.google.code.jcooky.chat.commons.jrc.SystemInfo;

public class Receiver implements Runnable {
	
	public static interface ReceiveListener {
		void onAddText(String text);
		void onEnterId(String id);
		void onCloseId(String id);
	}
	
	private ChatService service;
	private boolean closed = false;
	private String id;
	private List<ReceiveListener> listeners = new Vector<ReceiveListener>();
	
//	private Queue<String> textQ, enterQ, leaveQ;
	
	public Receiver(String id, ChatService service) {
		this.service = service;
		this.id = id;
		
//		textQ = new LinkedList<String>();
//		enterQ = new LinkedList<String>();
//		leaveQ = new LinkedList<String>();
	}
	
	public Receiver(String id, ChatService service, ReceiveListener l) {
		this(id, service);
		addReceiveListener(l);
	} 
	
	public void close() {
		closed = true;
	}
	
	public void addReceiveListener(ReceiveListener receiveListener) {
		synchronized(listeners) {
			listeners.add(receiveListener);
		}
	}
	
	private void addText(String str) {
		for(ReceiveListener l : listeners) {
			l.onAddText(str);
		}
	}
	
	private void addId(String id) {
		for(ReceiveListener l : listeners) {
			l.onEnterId(id);
		}
	}
	
	private void removeId(String id) {
		for(ReceiveListener l : listeners) {
			l.onCloseId(id);
		}
	}
	
	@Override
	public void run() {
		while(!closed) {
			recvMessage();
			recvSystemInfo();
			recvEnterUser();
			recvClosedUser();			
		}
	}
	
	private void recvMessage() {
		StringBuffer strbuf = new StringBuffer(128);
		List<Message> messages = service.getMessage(id);
		
		for(Message message : messages) {
			strbuf.append("\n").append(message.getFrom()).append(" : ").append(message.getMessage());
		}
		
		if(strbuf.length() != 0)
			addText(strbuf.toString());
	}
	
	private void recvEnterUser() { 
		List<String> ids = service.getEnterUser(id);
		
		for(String id : ids) {
			addId(id);
		}
	}
	
	private void recvSystemInfo() {
		StringBuffer strbuf = new StringBuffer(128);
		List<SystemInfo> systemInfos = service.getSystemInfo(id);
		for(SystemInfo si : systemInfos) {
			strbuf.append("\n").append("System(").append(si.getType()).append(") : ").append(si.getMessage());
			addText(strbuf.toString());
			strbuf.setLength(0);
		}
	}
	
	private void recvClosedUser() {
		List<String> ids = service.getClosedUser(id);
		
		for(String id : ids) {
			removeId(id);
		}
	}
}
